<template>
  <el-card class="box-card">
    <el-alert
      type="info"
      :closable="false"
      show-icon
      title="提现规则"
      description="提现金额按照手续费阶梯进行计算，满足阶梯1，则按照阶梯1计算，以此类推。"
    />
    <el-form
      ref="formRef"
      :label-position="'top'"
      label-width="160px"
      :model="formOpts"
      :rules="formOpts.rules"
      style="margin-top: 24px"
      v-loading="isLoading"
    >
      <el-form-item prop="limit.min">
        最低提现金额<el-input-number
          v-model="formOpts.data.limit.min"
          :min="1"
          :max="9999999999"
          :controls="false"
        />元
      </el-form-item>
      <el-form-item prop="limit.max">
        最高提现金额<el-input-number
          v-model="formOpts.data.limit.max"
          :min="1"
          :max="9999999999"
          :controls="false"
        />元
      </el-form-item>
      <el-form-item prop="limit.total">
        单日累计提现金额<el-input-number
          v-model="formOpts.data.limit.total"
          :min="1"
          :max="9999999999"
          :controls="false"
        />元
      </el-form-item>
      <el-form-item prop="limit.batch">
        单批次累计提现金额<el-input-number
          v-model="formOpts.data.limit.batch"
          :min="1"
          :max="9999999999"
          :controls="false"
        />元
      </el-form-item>

      <el-form-item
        v-for="(item, index) in formOpts.data.rules"
        :key="index"
        :label="'提现阶梯-第' + (index + 1) + '档：'"
      >
        <span>提现金额大于等于</span>
        <el-form-item :prop="'data.rules.' + index + '.min'">
          <el-input-number
            v-model="item.min"
            :min="1"
            :max="9999999999"
            :controls="false"
          />
        </el-form-item>
        <span>元，</span>

        <template v-if="index < formOpts.data.rules.length - 1">
          <span>小于</span>
          <el-form-item :prop="'data.rules.' + index + '.max'">
            <el-input-number
              v-model="item.max"
              :min="1"
              :max="9999999999"
              :controls="false"
            />
          </el-form-item>
          <span>元，</span>
        </template>

        <span>收取</span>
        <el-form-item :prop="'data.rules.' + index + '.charge'">
          <el-input-number
            v-model="item.charge"
            :min="1"
            :max="9999999999"
            :controls="false"
          />
        </el-form-item>
        <span>(%)的手续费</span>
      </el-form-item>

      <el-form-item label="描述（展示于小程序）" prop="remark">
        <el-input
          v-model="formOpts.data.remark"
          type="textarea"
          :rows="8"
          :maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-divider />

      <div>
        <el-button link @click="handleClickUseDefault()"
          >使用默认配置</el-button
        >
        <PipeResetBtn
          :formEl="formRef"
          @clear="handleClickReset"
          :loading="isLoading"
          >重置</PipeResetBtn
        >
        <el-button
          type="primary"
          @click="handleClickSubmit(formRef)"
          :loading="isLoading"
          >提交</el-button
        >
      </div>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { ElForm } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getSystemKvDetail, updateSystemKv } from '@/apis/system-kv';

interface SystemChargeRules {
  /** 最低 */
  min: number;
  /** 最大 */
  max?: number;
  /** 手续费(%) */
  charge: number;
}

interface FormData {
  limit: {
    min: number;
    max: number;
    // 单日累计限额
    total: number;
    // 单批次累计限额
    batch: number;
  };
  rules: SystemChargeRules[];
  remark: string;
}

interface FormOpts {
  data: FormData;
  rules: any;
}

// 加载状态
const isLoading = ref(false);

// 表单 - ref
const formRef = ref<InstanceType<typeof ElForm>>();

const formRules = reactive({
  min: [{ required: true, trigger: 'blur', message: '请输入最小值' }],
  max: [{ required: true, trigger: 'blur', message: '请输入最大值' }],
  total: [{ required: true, trigger: 'blur', message: '请输入单日累计金额' }],
  batch: [{ required: true, trigger: 'blur', message: '请输入单批次累计金额' }],
  charge: [{ required: true, trigger: 'blur', message: '请输入手续费（%）' }]
});

const formOpts: FormOpts = reactive({
  // 表单 - 数据
  data: {
    limit: {
      min: 10,
      max: 500,
      total: 20000,
      batch: 100000
    },
    rules: [],
    remark: ''
  },
  // 验证规则
  rules: formRules
});

// 详情
const detailData = ref<API.systemKv.EntitySchema>();

// btn - use default
const handleClickUseDefault = () => {
  // // 使用默认值
  // loopPropAssignment(formData, GetFormData());

  formOpts.data.limit.min = 1;
  formOpts.data.limit.max = 500;
  formOpts.data.limit.total = 20000;
  formOpts.data.limit.batch = 100000;
  formOpts.data.rules = [
    {
      min: 1000,
      max: 5000,
      charge: 1
    },
    {
      min: 5000,
      max: 10000,
      charge: 2
    },
    {
      min: 10000,
      charge: 5
    }
  ];
  formOpts.data.remark =
    '1.提现金额高于等于1000,低于5000时,按1%收取手续费;\n2.提现金额高于等于5000,低于10000时,按2%收取手续费;\n3.提现金额高于等于10000时,按5%收取手续费;';
};

// btn - reset
const handleClickReset = () => {
  requestDataDetail();
};

// btn - submit
const handleClickSubmit = async (
  formEl: InstanceType<typeof ElForm> | undefined
) => {
  // 二次确认
  try {
    await ElMessageBox.confirm(
      '设置后，新提现的申请才生效，是否设置？',
      '设置手续费',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
  } catch (error) {
    return;
  }

  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;

    submitDataUpdate();
  });
};

// submit - update
const submitDataUpdate = () => {
  const dataOpt = {
    // 组装数据
    value: JSON.stringify({
      limit: formOpts.data.limit,
      rules: formOpts.data.rules
    }),
    remark: formOpts.data.remark
  };

  isLoading.value = true;
  updateSystemKv(detailData.value?.key!, dataOpt)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
    })
    .catch(() => {
      isLoading.value = false;
    });
};

const requestDataDetail = () => {
  isLoading.value = true;
  getSystemKvDetail('system_charge')
    .then((res) => {
      isLoading.value = false;
      detailData.value = res.data;

      formOpts.data.remark = res.data?.remark ?? '';
      const resData = res.data?.value ? JSON.parse(res.data?.value) : null;
      if (resData) {
        formOpts.data.limit = resData.limit;
        formOpts.data.rules = resData.rules;
      }
    })
    .catch(() => {
      isLoading.value = false;
    });
};

requestDataDetail();
</script>

<style lang="scss" scoped></style>
